import axios from 'axios'
import router from '@/router/index'
import {Loading} from 'element-ui'
var loadingInstance;
var timeout;

import showAlert from '@/common/js/errorHandle'

import showLogin from '@/common/js/loginPop'

import showLoginTest from '@/common/js/loginTest'

export default{
	
    baseURI: function() {
        if (window.location.origin) {
            return window.location.origin;
        }
        return window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port: '')
       
    }(),
//  baseURI: function(){
//
//      return window.location.protocol + '//' + window.location.hostname + ':8081';
//     
//  }(),
    loadingInstance:null,
    // baseURI: "http://10.5.0.137:8080",
    baseURI: "http://10.5.0.137:9280",
    // baseURI: "http://192.168.191.1:19080",
    // baseURI: "http://192.168.100.84:19080",
    baseURI: "http://192.168.100.125:19080",
	Post : function(url, params,noLoading){
	
		//发送ajax请求
		return axios.request({
			method:  'POST',
			url : url,
			//params : params,微服务参数放在了url后
			// params:params,
			baseURL: this.baseURI,
			// params:params,
			
			timeout: 1500000,
			responseType: 'json',
			headers : {
                "Content-Type": "application/json"
			},
            data:params,
			transformRequest : function(data){
                // let ret = ''
		        // for (let it in data) {
		        //   ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
		        // }
                // let loadingInstance = Loading.service({fullscreen:HTMLOptGroupElement});
                // loadingInstance.close();
                data = data ? data : {};
                var token = localStorage.getItem("token");
                data.token = token ? token : '';
                if (!noLoading) {
                    if (!loadingInstance) {
                        timeout = setTimeout(function(){
                            loadingInstance && loadingInstance.close();
                            showAlert.showAlert("网络出错,请检查网路是否连接");
                        },150000)
                        loadingInstance = Loading.service({
                            target:'div.content', 
                            text:'加载中',
                            customclass:'load-mask'
                        });
                
                    }
                }

                return JSON.stringify(data);
			},
			transformResponse : function(response){
				// 这里提前处理返回的数据
				// if(response&&response.status&&response.status==='01'){
				// 	window.localStorage.removeItem('hyoaTK');
				// 	window.location.href='/module/login.html';
				// }
                typeof(response)==='string' && (response = JSON.parse(response)) 
//              && response.status !== 0
                if (response.status !== 1  && response.status !== 200) {
                    var message = response.message;
                    

                    if (response.status === 1005 || response.status === 1004) {
                    	if (location.hostname === '10.5.0.137' || location.hostname === 'localhost'  || location.hostname === '127.0.0.1') {
							showLoginTest.showLoginPanel(message);
						} else {
							showLogin.showLoginPanel(message);
						}
                        
                    } else {
                    	showAlert.showAlert(message);
                    }

//                  if (response.status === 1003 || response.status === 1004) {
//   
//                      router.push('/login');
//                  } 
                   
                }
        
                if (!loadingInstance) {
                    timeout = setTimeout(function(){
                        loadingInstance && loadingInstance.close();
                        showAlert.showAlert("网络出错,请检查网路是否连接");
                    },150000)
                    // loadingInstance = Loading.service({
                    //     target:'div.content', 
                    //     text:'加载中',
                    //     customclass:'load-mask'
                    // });
            
                }
                


                window.clearTimeout(timeout);
                timeout = null;
                loadingInstance && loadingInstance.close();
                loadingInstance = null;
				return response;
			},
			validateStatus: function (state) {
				//请求返回状态
         
    			return state >= 200 && state < 300;
			},
            withCredentials: true
		});
	},
    

    Get:function(url,params){
        // console.log(data,"data");
        params = params ? params : {};
        var token = localStorage.getItem("token");
        params.token = token ? token : '';
		return axios.request({
			method: 'GET',
			url : url,
			//params : params,微服务参数放在了url后
			// params:params,
			baseURL: this.baseURI,
			params:params,
			
			timeout: 15000,
			responseType: 'json',
			headers : {
                "Content-Type": "application/json"
			},
            transformRequest : function(data){
                let ret = ''
                console.log(data,"data");
                data = data ? data : {};
                var token = localStorage.getItem("token");
                data.token = token ? token : '';
		        for (let it in data) {
		          ret += it + '=' + data[it] + '&'
		        }

                console.log(ret);
                return ret;
                // let loadingInstance = Loading.service({fullscreen:HTMLOptGroupElement});
                // loadingInstance.close();
                // data = data ? data : {};
                // var token = localStorage.getItem("token");
                // data.token = token ? token : '';
                // if (!noLoading) {
                //     if (!loadingInstance) {
                //         timeout = setTimeout(function(){
                //             loadingInstance && loadingInstance.close();
                //             showAlert.showAlert("网络出错,请检查网路是否连接");
                //         },15000)
                //         loadingInstance = Loading.service({
                //             target:'div.content', 
                //             text:'加载中',
                //             customclass:'load-mask'
                //         });
                
                //     }
                // }

                // return JSON.stringify(data);
			},
			transformResponse : function(response){
				// 这里提前处理返回的数据

                typeof(response)==='string' && (response = JSON.parse(response)) 
            
				return response;
			},
			validateStatus: function (state) {
				//请求返回状态
                console.log(state,"state");
    			return state >= 200 && state < 300;
			},
            withCredentials: true
		});
    },

    StringPost:function(url,params){
    		//发送ajax请求
		return axios.request({
			method:  'POST',
			url : url,
			//params : params,微服务参数放在了url后
			// params:params,
			baseURL: this.baseURI,
			// params:params,
			
			timeout: 15000,
			responseType: 'json',
			headers : {
                "Content-Type": "application/json"
			},
            data:params,
			transformRequest : function(data){
                // let ret = ''
		        // for (let it in data) {
		        //   ret += it + '=' + data[it] + '&'
		        // }
                
                // return ret;
                data = data ? data : {};
                var token = localStorage.getItem("token");
                data.token = token ? token : '';
                return JSON.stringify(data);
			},
			transformResponse : function(response){
				// 这里提前处理返回的数据

				// if(response&&response.status&&response.status==='01'){
				// 	window.localStorage.removeItem('hyoaTK');
				// 	window.location.href='/module/login.html';
				// }
                typeof(response)==='string' && (response = JSON.parse(response)) 
                
				return response;
			},
			validateStatus: function (state) {
				//请求返回状态
                console.log(state,"state");
    			return state >= 200 && state < 300;
			},
            withCredentials: true
		});    
    },
    //以FormData形式发送POST请求，可用来上传文件
    axiosPostFormData : function(url,form){
        //发送ajax请求
        return axios.post(
        url,
        form,
        {
            method: 'post',
            baseURL: this.baseURI,
            headers: {"Content-Type": "multipart/form-data"},
            transformRequest : function(data){
            // 这里可以在发送请求之前对请求数据做处理，比如form-data格式化等，这里可以使用开头引入的Qs（这个模块在安装axios的时候就已经安装了，不需要另外安装）
            if(data && data instanceof FormData){
            }else{
                let formdata = new FormData();
                let i = 0;
                for (let it in data) {
                formdata.append(it, data[it]);
                }
                return formdata;
            }
            return data;
            },
            transformResponse : function(response){
            // 这里提前处理返回的数据
            if(response&&response.status&&response.status==='01'){
                window.localStorage.removeItem('hyoaTK');
                window.location.href='/module/login.html';
            }
            var res;
            if(typeof(response)==='string'){
                res=JSON.parse(response);
            }else{
                res=response;
            }
            var result = {
                status : status,
                data : res
            };
            return result;
            }
        }
        );
    }
}
